package fifth.cases;

class Link {
    class Node {
        private String data;
        private Node next;

        public Node(String data) {
            this.data = data;
        }

        public void add(Node node) {
            if (next == null) {
                this.next = node;
            } else {
                this.next.add(node);
            }
        }

        public void print() {
            System.out.print(this.data+"\t");
            if (this.next != null) {
                this.next.print();
            }
        }

        public boolean search(String data) {
            if (data.equals(this.data)) {
                return true;
            } else {
                if (this.next != null) {
                    return this.next.search(data);
                } else {
                    return false;
                }
            }
        }

        public void delete(Node previous, String data) {
            if (this.data.equals(data)) {
                previous.next = this.next;
            } else {
                if (this.next != null) {
                    this.delete(this, data);
                }
            }
        }
    }

    private Node root;

    public void addNode(String data) {
        Node n = new Node(data);
        if (root == null) {
            this.root = n;
        } else {
            this.root.add(n);
        }
    }

    public void printNode() {
        if (this.root != null) {
            this.root.print();
        }
    }

    public boolean contains(String data){
        return this.root.search(data);
    }
    public void deleteNode(String data) {
      if(this.contains(data)){
            if(this.root.data.equals(data)){
                this.root=this.root.next;
            }else{
                this.root.next.delete(root,data);
            }
        }
    }
}

public class 单项链表的实现_链表操作 {
    public static void main(String[] args) {
        Link l =  new Link();
        l.addNode("A");//添加节点
        l.addNode("B");
        l.addNode("C");
        l.addNode("D");
        l.addNode("E");
        System.out.println("========= 删除之前 ========");
        l.printNode();//打印节点
        l.deleteNode("B");
        l.deleteNode("C");
        System.out.println();
        System.out.println("========= 删除之后 ========");
        l.printNode();
        System.out.println("查询节点："+l.contains("A"));
    }
}